/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.hl_project.web;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.hl_project.entity.AjzProjectInfo;
import com.jeesite.modules.hl_project.entity.Map;
import com.jeesite.modules.hl_project.service.AjzProjectInfoService;
import com.jeesite.modules.sys.utils.DictUtils;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import static com.jeesite.modules.hl_project.entity.Map.*;

/**
 * 项目信息Controller
 * @author cww
 * @version 2019-01-21
 */
@Controller
@RequestMapping(value = "${adminPath}/hl_project/ajzProjectInfo")
public class AjzProjectInfoController extends BaseController {

	@Autowired
	private AjzProjectInfoService ajzProjectInfoService;
	
	/**
	 * 获取数据
	 */
	@ModelAttribute
	public AjzProjectInfo get(String id, boolean isNewRecord) {
		return ajzProjectInfoService.get(id, isNewRecord);
	}
	
	/**
	 * 查询列表
	 */
	@RequiresPermissions("hl_project:ajzProjectInfo:view")
	@RequestMapping(value = {"list", ""})
	public String list(AjzProjectInfo ajzProjectInfo, Model model) {
		model.addAttribute("ajzProjectInfo", ajzProjectInfo);
		return "modules/hl_project/ajzProjectInfoList";
	}
	
	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("hl_project:ajzProjectInfo:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<AjzProjectInfo> listData(AjzProjectInfo ajzProjectInfo, HttpServletRequest request, HttpServletResponse response) {
		ajzProjectInfo.setPage(new Page<>(request, response));
		Page<AjzProjectInfo> page = ajzProjectInfoService.findPage(ajzProjectInfo);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("hl_project:ajzProjectInfo:view")
	@RequestMapping(value = "form")
	public String form(AjzProjectInfo ajzProjectInfo, Model model) {
		model.addAttribute("ajzProjectInfo", ajzProjectInfo);

		return "modules/hl_project/ajzProjectInfoForm";
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("hl_project:ajzProjectInfo:view")
	@RequestMapping(value = "form1")
	public String form1(AjzProjectInfo ajzProjectInfo, Model model) {
		model.addAttribute("ajzProjectInfo", ajzProjectInfo);
		return "modules/hl_project/ajzProjectInfoForm1";
	}

	/**
	 * 保存项目信息
	 */
	@RequiresPermissions("hl_project:ajzProjectInfo:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated AjzProjectInfo ajzProjectInfo) {
		ajzProjectInfoService.save(ajzProjectInfo);
		String name = ajzProjectInfo.getProjectName();
		String address = ajzProjectInfo.getAddress();
		if(address!=null||"".equals(address)){
			send(name,address);
		}
		return renderResult(Global.TRUE, text("保存项目信息成功！"));
	}
	
	/**
	 * 删除项目信息
	 */
	@RequiresPermissions("hl_project:ajzProjectInfo:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(AjzProjectInfo ajzProjectInfo) {
		ajzProjectInfoService.delete(ajzProjectInfo);
		return renderResult(Global.TRUE, text("删除项目信息成功！"));
	}

	/**
	 * 地图标点展示
	 */
	@RequiresPermissions("hl_project:ajzProjectInfo:view")
	@RequestMapping(value = "mapShow")
	public String mapShow() {
		return "modules/hl_project/mapShow";
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("hl_project:ajzProjectInfo:view")
	@RequestMapping(value = "Addform")
	public String formAdd(AjzProjectInfo ajzProjectInfo, Model model) {
		model.addAttribute("ajzProjectInfo", ajzProjectInfo);

		return "modules/hl_project/ajzProjectInfoForm_AddText";
	}

	/**
	 * 列表上图
	 *　　sendUrl    （远程请求的URL）
	 *　　param    （远程请求参数）
	 *　　JSONObject    （远程请求返回的JSON）
	 */
	private JSONObject sendPostUrl(String url, String param){
		PrintWriter out = null;
		BufferedReader in = null;
		JSONObject jsonObject = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流（设置请求编码为UTF-8）
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 获取请求返回数据（设置返回数据编码为UTF-8）
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			jsonObject = JSONObject.fromObject(result);
			System.out.println(jsonObject);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try{
				if(out!=null){
					out.close();
				}
				if(in!=null){
					in.close();
				}
			}
			catch(IOException ex){
				ex.printStackTrace();
			}
		}

		return jsonObject;
	}

	public JSONObject send(String name, String address){
		Map data = new Map();
		data.set_name(name);
		data.set_address(address);
		String params = "key=" + KEY+ "&tableid=" + TABLEID+"&loctype="+LOCTYPE+"&data="+data;
		JSONObject jsonObject = sendPostUrl("https://yuntuapi.amap.com/datamanage/data/create", params);
		return jsonObject;
	}

	/**
	 * 下载导入企业数据模板
	 */
	@RequestMapping(value = "importTemplate")
	public void shipinTemplate(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {

		try {
			String fileName = "项目模板.xlsx";
			String realPath = request.getSession().getServletContext().getRealPath("/downLoad/项目模板.xlsx");
			downLoadFile(realPath, response, fileName);
//			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息：" + e.getMessage());
		}
//		return "redirect:" + adminPath + "/ajz/ajzBaseinfo/list?repage";
	}

	/**
	 * 导入用户数据
	 */
	@ResponseBody
	@RequiresPermissions("hl_project:ajzProjectInfo:view")
	@PostMapping(value = "importData")
	public String importData(MultipartFile file, String updateSupport) {
		try {
			boolean isUpdateSupport = Global.YES.equals(updateSupport);
			String message = ajzProjectInfoService.importData(file, isUpdateSupport);
			return renderResult(Global.TRUE, "posfull:"+message);
		} catch (Exception ex) {
			return renderResult(Global.FALSE, "posfull:"+ex.getMessage());
		}
	}

	/**
	 * 文件下载
	 *
	 * @param filePath
	 * @param response
	 * @param filename
	 */
	@SuppressWarnings("resource")
	public void downLoadFile(String filePath, HttpServletResponse response, String filename) {
		BufferedOutputStream bufferOut = null;
		BufferedInputStream bufferIn = null;
		try {
			bufferIn = new BufferedInputStream(new FileInputStream(filePath));
			bufferOut = new BufferedOutputStream(response.getOutputStream());
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("UTF-8"), "iso8859-1"));
			byte[] Byte = new byte[1024];
			int len = 0;
			while (-1 != (len = bufferIn.read(Byte))) {
				bufferOut.write(Byte, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != bufferOut) {
				try {
					bufferOut.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != bufferIn) {
				try {
					bufferIn.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 导出用户数据
	 */
	@RequestMapping(value = "exportData")
	public void exportData(AjzProjectInfo ajzProjectInfo, HttpServletResponse response) {
		List<AjzProjectInfo> list = ajzProjectInfoService.findList(ajzProjectInfo);
		//用于处理字典值
		List<AjzProjectInfo> list1 = new ArrayList<AjzProjectInfo>();
		for (AjzProjectInfo ajzProjectInfo1:list){
			ajzProjectInfo1.setProjectType(DictUtils.getDictLabel("project_type",ajzProjectInfo1.getProjectType(),"type1"));
			ajzProjectInfo1.setStreet(DictUtils.getDictLabel("hlq_street",ajzProjectInfo1.getStreet(),"street_hl"));
			list1.add(ajzProjectInfo1);
		}
		String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try(ExcelExport ee = new ExcelExport("用户数据", AjzProjectInfo.class)){
			ee.setDataList(list).write(response, fileName);
		}
	}
}